import { lazyReport } from '../report/report';

// 全局错误捕获,错误分为五种
//语法错误,直接编译器报错，无法try catch捕获
//同步错误,try catch可以捕获
//异步错误 try catch不会捕获，用onError处理
//promise错误
//resource错误
export function errorTrackerReport() {
  const originOnError = window.onerror;
  // 处理异步错误上报
  window.onerror = function (msg, url, row, col, error) {
    // 处理原有的onerror，因为onerror会被覆盖
    if (originOnError) {
      originOnError.call(window, msg, url, row, col, error);
    }
    lazyReport('error', {
      message: msg,
      file: url,
      row,
      col,
      error,
      errorType: 'jsError'
    });
  }

  // 处理promise报错
  window.addEventListener('unhandledrejection', (error) => {
    lazyReport('error', {
      message: error.reason,
      error,
      errorType: 'promiseError'
    });
  });

  //处理资源报错
  window.addEventListener('error', (error) => {
    let target = error.target;
    //如果是script link img就断定为资源问题
    let isElementTarget = target instanceof HTMLScriptElement || target instanceof HTMLLinkElement || target instanceof HTMLImageElement;
    if (!isElementTarget) {
      return;
    }
    lazyReport('error', {
      message: "加载 " + target.tagName + " 资源错误",
      file: target.src,
      errorType: 'resourceError'
    });
  }, true)
}

/**
 * 手动捕获错误
 */
export function errorCaptcher(error, msg) {
  // 上报错误
  lazyReport('error', {
    message: msg,
    error: error,
    errorType: 'catchError'
  });
}